package com.xx.happychatboot.middleware.netty.handller;

import cn.hutool.json.JSONUtil;
import com.xx.happychatboot.middleware.netty.domain.vo.request.WebSocketRequest;
import com.xx.happychatboot.middleware.netty.factory.websocket.WebSocketFactory;
import com.xx.happychatboot.middleware.netty.strategy.websocket.AbstractWebsocketStrategy;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * netty自定义拦截器处理webSocket请求  ----> 用于处理业务逻辑
 */
@Slf4j
// 用来标识一个ChannelHandler可以被多个Channel共享的注解
@ChannelHandler.Sharable
public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext,
                                TextWebSocketFrame msg) throws Exception {
        // 读取客户端发送的消息 ---> 转化为WebSocketRequest对象
        WebSocketRequest wsBaseReq = JSONUtil.toBean(msg.text(), WebSocketRequest.class);
        if (Objects.isNull(wsBaseReq) || Objects.isNull(wsBaseReq.getType())) {
            log.error("请求参数为空");
            return;
        }
        // 获取对应的策略
        AbstractWebsocketStrategy strategy = WebSocketFactory.getStrategyNoNull(wsBaseReq.getType());

        if (Objects.isNull(strategy)) {
            log.error("未找到对应策略");
            return;
        }

        // 处理前端发送过来的消息
        strategy.execute(channelHandlerContext, wsBaseReq.getData());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        log.info("Netty server started and channel is active: {}", ctx.channel().remoteAddress());
    }
}
